import { DIContainer, SERVICE_TOKENS } from '../infrastructure/di';
import { ServiceManager } from './base';

// 导入现代化Service类
import { BagService } from './BagService';
import { ModernBagService } from './ModernBagService';
import { RPGService } from './RPGService';
import { ModernRPGService } from './ModernRPGService';
import { ModernTaskService } from './ModernTaskService';
import { EquipService } from './EquipService';
import { ModernSignService } from './ModernSignService';
import { ModernTalentService } from './ModernTalentService';
import { ModernPopupService } from './ModernPopupService';
import { ModernIntentService } from './ModernIntentService';
import { ModernRankingService } from './ModernRankingService';
import { BagRepository } from '../repository/BagRepository';
import { RPGRepository } from '../repository/RPGRepository';
import { TaskRepository } from '../repository/TaskRepository';
import { PropRepository } from '../repository/PropRepository';
import { EquipRepository } from '../repository/EquipRepository';
import { MarketRepository } from '../repository/MarketRepository';
import ModernPropService from './ModernPropService';
import { ModernEquipService } from './ModernEquipService';
import { ModernMarketService } from './ModernMarketService';

/**
 * Service注册中心
 * 负责注册和配置所有Service实例
 */
export class ServiceRegistry {
    private static container: DIContainer;
    private static initialized = false;

    /**
     * 初始化Service注册中心
     * @param container DI容器实例
     */
    static initialize(container: DIContainer): void {
        if (this.initialized) {
            console.warn('ServiceRegistry already initialized');
            return;
        }

        this.container = container;
        this.registerCoreServices();
        this.initialized = true;
        
        console.log('ServiceRegistry initialized successfully');
    }

    /**
     * 注册核心业务Service
     */
    private static registerCoreServices(): void {
        console.log('Registering core services...');

        // 注册背包仓储
        this.container.register(
            SERVICE_TOKENS.BAG_REPOSITORY,
            (container) => new BagRepository(container),
            { singleton: true, lifecycle: 'eager' }
        );

        // 注册道具仓储
        this.container.register(
            'PropRepository',
            (container) => new PropRepository(container),
            { singleton: true, lifecycle: 'eager' }
        );

        // 注册装备仓储
        this.container.register(
            'EquipRepository',
            (container) => new EquipRepository(container),
            { singleton: true, lifecycle: 'eager' }
        );

        // 注册市场仓储
        this.container.register(
            'MarketRepository',
            (container) => new MarketRepository(container),
            { singleton: true, lifecycle: 'eager' }
        );

        // 注册现代化背包服务
        this.container.register(
            'ModernBagService',
            (container) => new ModernBagService(container),
            { singleton: true, lifecycle: 'eager' }
        );

        // 注册背包服务（兼容性包装器）
        this.container.register(
            SERVICE_TOKENS.BAG_SERVICE,
            (container) => new BagService(container),
            { singleton: true, lifecycle: 'eager' }
        );

        // 注册RPG仓储
        this.container.register(
            SERVICE_TOKENS.RPG_REPOSITORY,
            (container) => new RPGRepository(container),
            { singleton: true, lifecycle: 'eager' }
        );

        // 注册现代化RPG服务
        this.container.register(
            'ModernRPGService',
            (container) => new ModernRPGService(container),
            { singleton: true, lifecycle: 'eager' }
        );

        // 注册RPG服务（兼容性包装器）
        this.container.register(
            SERVICE_TOKENS.RPG_SERVICE,
            (container) => new RPGService(container),
            { singleton: true, lifecycle: 'eager' }
        );

        // 注册任务仓储
        this.container.register(
            SERVICE_TOKENS.TASK_REPOSITORY,
            (container) => new TaskRepository(container),
            { singleton: true, lifecycle: 'eager' }
        );

        // 注册现代化任务服务
        this.container.register(
            'ModernTaskService',
            (container) => new ModernTaskService(container),
            { singleton: true, lifecycle: 'eager' }
        );

        // 注册任务服务（兼容性包装器）
        this.container.register(
            SERVICE_TOKENS.TASK_SERVICE,
            (container) => new ModernTaskService(container),
            { singleton: true, lifecycle: 'eager' }
        );

        // 注册现代化装备服务
        this.container.register(
            'ModernEquipService',
            (container) => new ModernEquipService(container),
            { singleton: true, lifecycle: 'lazy' }
        );

        // 注册现代化市场服务
        this.container.register(
            'ModernMarketService',
            (container) => new ModernMarketService(container),
            { singleton: true, lifecycle: 'lazy' }
        );

        // 注册装备服务
        this.container.register(
            'EquipService',
            (container) => new EquipService(),
            { singleton: true, lifecycle: 'lazy' }
        );

        // 注册现代化签到服务
        this.container.register(
            'ModernSignService',
            (container) => new ModernSignService(container),
            { singleton: true, lifecycle: 'lazy' }
        );

        // 注册现代化血统服务
        this.container.register(
            'ModernTalentService',
            (container) => new ModernTalentService(container),
            { singleton: true, lifecycle: 'lazy' }
        );

        // 注册现代化弹窗服务
        this.container.register(
            'ModernPopupService',
            (container) => new ModernPopupService(container),
            { singleton: true, lifecycle: 'lazy' }
        );

        // 注册现代化意图服务
        this.container.register(
            'ModernIntentService',
            (container) => new ModernIntentService(container),
            { singleton: true, lifecycle: 'lazy' }
        );

        // 注册现代化排行榜服务
        this.container.register(
            'ModernRankingService',
            (container) => new ModernRankingService(container),
            { singleton: true, lifecycle: 'lazy' }
        );

        // 注册现代化道具服务
        this.container.register(
            'ModernPropService',
            (container) => new ModernPropService(container),
            { singleton: true, lifecycle: 'lazy' }
        );

        console.log('Core services registered successfully');
    }

    /**
     * 注册所有Service到ServiceManager
     */
    static async registerToServiceManager(): Promise<void> {
        if (!this.initialized) {
            throw new Error('ServiceRegistry not initialized. Call initialize() first.');
        }

        console.log('Registering services to ServiceManager...');

        // 获取所有已注册的Service实例
        const bagRepository = this.container.get<BagRepository>(SERVICE_TOKENS.BAG_REPOSITORY);
        const modernBagService = this.container.get<ModernBagService>('ModernBagService');
        const bagService = this.container.get<BagService>(SERVICE_TOKENS.BAG_SERVICE);
        const rpgRepository = this.container.get<RPGRepository>(SERVICE_TOKENS.RPG_REPOSITORY);
        const modernRPGService = this.container.get<ModernRPGService>('ModernRPGService');
        const rpgService = this.container.get<RPGService>(SERVICE_TOKENS.RPG_SERVICE);
        const taskRepository = this.container.get<TaskRepository>(SERVICE_TOKENS.TASK_REPOSITORY);
        const modernTaskService = this.container.get<ModernTaskService>('ModernTaskService');
        const taskService = this.container.get<ModernTaskService>(SERVICE_TOKENS.TASK_SERVICE);
        const equipService = this.container.get<EquipService>('EquipService');

        // 注册到ServiceManager
        ServiceManager.registerService('BagRepository', bagRepository);
        ServiceManager.registerService('ModernBagService', modernBagService);
        ServiceManager.registerService('BagService', bagService);
        ServiceManager.registerService('RPGRepository', rpgRepository);
        ServiceManager.registerService('ModernRPGService', modernRPGService);
        ServiceManager.registerService('RPGService', rpgService);
        ServiceManager.registerService('TaskRepository', taskRepository);
        ServiceManager.registerService('ModernTaskService', modernTaskService);
        ServiceManager.registerService('TaskService', taskService);
        ServiceManager.registerService('EquipService', equipService);

        console.log('Services registered to ServiceManager successfully');
    }

    /**
     * 启动所有Service
     */
    static async startAllServices(): Promise<void> {
        if (!this.initialized) {
            throw new Error('ServiceRegistry not initialized. Call initialize() first.');
        }

        console.log('Starting all services...');

        try {
            // 首先注册到ServiceManager
            await this.registerToServiceManager();

            // 然后初始化所有Service
            await ServiceManager.initializeAll();

            console.log('All services started successfully');
        } catch (error) {
            console.error('Failed to start services:', error);
            throw error;
        }
    }

    /**
     * 停止所有Service
     */
    static async stopAllServices(): Promise<void> {
        console.log('Stopping all services...');

        try {
            await ServiceManager.destroyAll();
            console.log('All services stopped successfully');
        } catch (error) {
            console.error('Failed to stop services:', error);
            throw error;
        }
    }

    /**
     * 获取Service实例
     * @param token Service令牌
     * @returns Service实例
     */
    static getService<T>(token: string): T {
        if (!this.initialized) {
            throw new Error('ServiceRegistry not initialized. Call initialize() first.');
        }

        return this.container.get<T>(token);
    }

    /**
     * 获取DI容器实例
     */
    static getContainer(): DIContainer {
        if (!this.initialized) {
            throw new Error('ServiceRegistry not initialized. Call initialize() first.');
        }

        return this.container;
    }

    /**
     * 获取Service状态报告
     */
    static getStatusReport(): {
        registry: {
            initialized: boolean;
            containerServices: string[];
        };
        serviceManager: {
            total: number;
            ready: number;
            notReady: number;
            services: Array<{ name: string; ready: boolean }>;
        };
        container: {
            isValid: boolean;
            errors: string[];
            warnings: string[];
        };
    } {
        const containerServices = this.initialized ? this.container.getRegisteredServices() : [];
        const serviceManagerStatus = ServiceManager.getServiceStatus();
        const containerValidation = this.initialized ? this.container.validateDependencies() : {
            isValid: false,
            errors: ['Container not initialized'],
            warnings: []
        };

        return {
            registry: {
                initialized: this.initialized,
                containerServices
            },
            serviceManager: serviceManagerStatus,
            container: containerValidation
        };
    }

    /**
     * 重新加载指定Service
     * @param serviceName Service名称
     */
    static async reloadService(serviceName: string): Promise<void> {
        if (!this.initialized) {
            throw new Error('ServiceRegistry not initialized. Call initialize() first.');
        }

        console.log(`Reloading service: ${serviceName}`);

        try {
            await ServiceManager.restartService(serviceName);
            console.log(`Service reloaded successfully: ${serviceName}`);
        } catch (error) {
            console.error(`Failed to reload service ${serviceName}:`, error);
            throw error;
        }
    }

    /**
     * 健康检查
     */
    static async healthCheck(): Promise<{
        healthy: boolean;
        issues: string[];
        services: Record<string, boolean>;
    }> {
        const issues: string[] = [];
        const services: Record<string, boolean> = {};

        if (!this.initialized) {
            issues.push('ServiceRegistry not initialized');
            return { healthy: false, issues, services };
        }

        // 检查Service状态
        const serviceStatus = ServiceManager.getServiceStatus();
        serviceStatus.services.forEach(service => {
            services[service.name] = service.ready;
            if (!service.ready) {
                issues.push(`Service ${service.name} is not ready`);
            }
        });

        // 检查容器依赖
        const containerValidation = this.container.validateDependencies();
        if (!containerValidation.isValid) {
            issues.push(...containerValidation.errors);
        }

        const healthy = issues.length === 0;
        
        console.log(`Health check completed: ${healthy ? 'HEALTHY' : 'UNHEALTHY'}`);
        if (!healthy) {
            console.warn('Health check issues:', issues);
        }

        return { healthy, issues, services };
    }
}
